package com.oolatina;

import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;

public class SCAudioPlayer implements OnCompletionListener, OnBufferingUpdateListener
{
	MediaPlayer mediaPlayer;
	final Handler uiThreadCallback = new Handler();
	protected ProgressDialog myProgressDialog;
	Context _context;
	String _url;
	Boolean _autoplay;
	
	public void init(Context thisContext)
	{
		_context = thisContext;
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnBufferingUpdateListener(this);
		mediaPlayer.setOnCompletionListener(this);
	}
	
	public void SetURL(String url, Boolean autoplay)
	{
		_url = url;
		_autoplay = autoplay;
		
		if(!mediaPlayer.isPlaying())
		{
			mediaPlayer.stop();
		}
		mediaPlayer = null;
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnBufferingUpdateListener(this);
		mediaPlayer.setOnCompletionListener(this);
		
		myProgressDialog = ProgressDialog.show(_context, "Chargement", "Veuillez patientez");		
	 
	    final Runnable runInUIThread = new Runnable() 
	    {
	    	public void run() 
	    	{
	    	     //affiche_liste();    	     
	    	}
	    };
	 
	    new Thread() 
	    {
	    	@Override public void run() 
	    	{
	    		try 
	    		{
	    			mediaPlayer.setDataSource(_url);
	    			mediaPlayer.prepare();
	    			if(_autoplay)
	    			{
	    				mediaPlayer.start();
	    			}
	    			myProgressDialog.dismiss();
	    		}
	    		catch (Exception e)
	    		{
	    			e.printStackTrace();
	    		}
	    		uiThreadCallback.post(runInUIThread);
	    	}
	    }.start();
	 
		
		/*try 
		{
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare();
			if(autoplay)
			{
				mediaPlayer.start();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}*/
	}
	
	public void SetPlay()
	{
		if(!mediaPlayer.isPlaying())
		{
			mediaPlayer.start();
		}
		else
		{
			mediaPlayer.pause();
		}
	}
	
	public void SetForcePlay()
	{
		mediaPlayer.start();
	}
	
	public void SetStop()
	{
		mediaPlayer.stop();
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) 
	{
		/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
		//buttonPlayPause.setImageResource(R.drawable.button_play);
	}
	 
	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) 
	{
		/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
		//seekBarProgress.setSecondaryProgress(percent);
	}
}
